import os
from ogreEx.blender.props import StringProperty, BoolProperty
from ogreEx.blender.types import Operator
from ogreEx.context import getTundraSingleton, setTundraSingleton
from ogreEx.ogre.C_OgreCommonExport_ import _OgreCommonExport_
from ogreEx.ogre.mesh import export_mesh
from ogreEx.tundra.TundraPipe import TundraPipe
from ogreEx.ui.UIClass import OPERATOR


## realXtend Tundra preview
## todo: This only work if the custom py script is enabled in Tundra
## It's nice when it works but PythonScriptModule is not part of the
## default Tundra distro anymore, so this is atm kind of dead.

@OPERATOR
class TundraPreviewOp(_OgreCommonExport_, Operator):
    '''helper to open Tundra2 (realXtend)'''
    bl_idname = 'tundra.preview'
    bl_label = "opens Tundra2 in a non-blocking subprocess"
    bl_options = {'REGISTER'}
    filepath= StringProperty(name="File Path", description="Filepath used for exporting Tundra .txml file", maxlen=1024, default="/tmp/preview.txml", subtype='FILE_PATH')
    EXPORT_TYPE = 'REX'
    EX_FORCE_CAMERA = BoolProperty(name="Force Camera", description="export active camera", default=False)
    EX_FORCE_LAMPS = BoolProperty(name="Force Lamps", description="export all lamps", default=False)

    @classmethod
    def poll(cls, context):
        if context.active_object and context.mode != 'EDIT_MESH':
            return True

    def invoke(self, context, event):
        syncmats = []
        obs = []
        if getTundraSingleton():
            actob = context.active_object
            obs = getTundraSingleton().deselect_previously_updated(context)
            for ob in obs:
                if ob.type=='MESH':
                    syncmats.append( ob )
                    if ob.name == actob.name:
                        export_mesh( ob, path='/tmp/rex' )

        if not os.path.isdir( '/tmp/rex' ): os.makedirs( '/tmp/rex' )
        path = '/tmp/rex/preview.txml'
        self.ogre_export( path, context, force_material_update=syncmats )
        if not getTundraSingleton():
            setTundraSingleton(TundraPipe(context))
        elif self.EX_SCENE:
            getTundraSingleton().load(context, path)

        for ob in obs:
            ob.select = True # restore selection
        return {'FINISHED'}